package top.mcwebsite.playandroid.lib.markdown.render

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.ast.findChildOfType
import top.mcwebsite.playandroid.lib.markdown.BlockVerticalPadding
import top.mcwebsite.playandroid.lib.markdown.utils.intToRoman
import top.mcwebsite.playandroid.lib.markdown.utils.numberToLetters

@Composable
fun OrderedList(
    astNode: ASTNode,
    markdownState: MarkdownState,
    modifier: Modifier = Modifier,
    level: Int = 1,
) {
    Column(
        modifier = modifier.padding(vertical = BlockVerticalPadding)
    ) {
        var index = 1
        astNode.children.forEach {
            when (it.type) {
                MarkdownElementTypes.LIST_ITEM -> OrderedListItem(
                    astNode = it,
                    markdownState = markdownState,
                    index++,
                    level
                )
            }
        }
    }
}

@Composable
fun OrderedListItem(astNode: ASTNode, markdownState: MarkdownState, index: Int, level: Int) {
    Column {
        Row {
            Text(text = "${getTextWithIndexLevel(index, level)}.")
            astNode.findChildOfType(MarkdownElementTypes.PARAGRAPH)?.let {
                RichText(
                    markdownState = markdownState,
                    astNode = it,
                    style = TextStyle(),
                    modifier = Modifier.padding(start = 5.dp)
                )
            }
        }

        astNode.findChildOfType(MarkdownElementTypes.UNORDERED_LIST)?.let {
            UnOrderedList(astNode = it, markdownState = markdownState, modifier = Modifier.padding(start = 30.dp))
        }
        astNode.findChildOfType(MarkdownElementTypes.ORDERED_LIST)?.let {
            OrderedList(
                astNode = it,
                markdownState = markdownState,
                modifier = Modifier.padding(start = 30.dp),
                level + 1
            )
        }
    }
}

private fun getTextWithIndexLevel(index: Int, level: Int): String {
    return when (level) {
        1 -> index.toString()
        2 -> numberToLetters(index)
        else -> intToRoman(index)
    }
}